// 学习概览统计API
import { NextRequest } from 'next/server';
import { StatsDB } from '@/lib/mysql';
import { getCurrentUser, ApiResponse } from '@/lib/auth';

// 获取用户学习概览
export async function GET(request: NextRequest) {
  try {
    // 验证用户登录
    const currentUser = getCurrentUser();
    if (!currentUser) {
      return ApiResponse.unauthorized('请先登录');
    }

    // 获取学习概览
    const overview = await StatsDB.getUserOverview(currentUser.userId);

    if (!overview) {
      return ApiResponse.success({
        userId: currentUser.userId,
        username: currentUser.username,
        topicsLearned: 0,
        totalQuestions: 0,
        correctAnswers: 0,
        accuracyRate: 0,
        totalTime: 0,
        lastPracticeTime: null,
      });
    }

    // 将数据库字段(snake_case)转换为前端期望的camelCase
    const mapped = {
      userId: overview.user_id,
      username: overview.username,
      displayName: overview.display_name,
      topicsLearned: overview.topics_learned || 0,
      totalQuestions: overview.total_questions || 0,
      correctAnswers: overview.correct_answers || 0,
      accuracyRate: overview.accuracy_rate || 0,
      totalTime: overview.total_time || 0,
      lastPracticeTime: overview.last_practice_time || null,
    };

    return ApiResponse.success(mapped);
  } catch (error) {
    console.error('获取学习概览错误:', error);
    return ApiResponse.serverError('获取学习概览失败');
  }
}
